package com.x.mvp.utils;

import android.os.Environment;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by H on 17/5/20.
 */

public class FileHelper {
    public static String saveBytesToFile(InputStream is, String path) {
        String filename = null;
        try {
            filename = saveBytesToFile(getBytesFromStream(is), path);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return filename;

    }

    public static byte[] getBytesFromStream(InputStream is) throws IOException {

        int len;
        int size = 1024;
        byte[] buf;

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        buf = new byte[size];
        while ((len = is.read(buf, 0, size)) != -1) {
            bos.write(buf, 0, len);
        }
        buf = bos.toByteArray();

        return buf;
    }

    public static String saveBytesToFile(byte[] bytes, String path) {
        FileOutputStream fileOuputStream = null;
        File appDir = new File(Environment.getExternalStorageDirectory(), "Hongniu");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + path + ".jpg";
        File file = new File(appDir, fileName);
        try {
            fileOuputStream = new FileOutputStream(file);
            fileOuputStream.write(bytes);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileOuputStream != null) {
                try {
                    fileOuputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return fileName;
    }
}
